#include "PayBox.h"
#include <Arduino.h>
#include <AudioFileSourceHTTPStream.h>
#include <AudioGeneratorMP3.h>
#include <AudioOutputI2S.h>
#include <SD.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <WiFi.h>

AudioGeneratorMP3 *mp3;
AudioFileSourceHTTPStream *file;
AudioOutputI2S *out;

TFT_eSPI tft = TFT_eSPI();
char buf[32] = {0};
unsigned long lastMs = 0;
char mute = 0;
const char *url = "http://webfs.ali.kugou.com/202108072023/a8c483c7550a13f43e559fda857ddfab/KGTX/CLTX001/1b3002aa6d5574f2daf6b22ad31c7aa4.mp3";

void playCurMusic() {
  tft.drawCentreString("Play MP3 Music", 160, 80, 4);
  tft.drawRoundRect(40, 120, 240, 10, 3, TFT_RED);
  file->open(url);
  mp3->begin(file, out);
}

void setupAudioPlay() {
  audioLogger = &Serial;
  file = new AudioFileSourceHTTPStream();
  out = new AudioOutputI2S();
  out->SetPinout(PAY_AUDIO_SCLK, PAY_AUDIO_LRCK, PAY_AUDIO_SDATA);
  //设置增益
  out->SetGain(0.08f);
  mp3 = new AudioGeneratorMP3();
  playCurMusic();
  payAudioInit();
}

void setup() {
  Serial.begin(115200);
  payTFTInit(tft, 32);
  payLEDInit();
  payLEDShow(0xf6229a);
  tft.println("Start Wifi Connect!");
  autoConfigWifi();
  tft.println("Wifi Connected!");
  sprintf(buf, "IP: %s", WiFi.localIP().toString().c_str());
  tft.println(buf);
  setupOTAConfig();
  delay(1000);
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE, TFT_BLACK);
  tft.drawCentreString(buf, 160, 220, 2);
  setupAudioPlay();
  // 重启按钮
  bindKeyEvent(PAY_KEY_ON, [] {
    payAudioDisable();
    ESP.restart();
  });
  bindKeyEvent(PAY_KEY_REFRESH, [] {
    mute = 1 - mute;
    if (mute) {
      payAudioDisable();
    } else {
      payAudioEnable();
    }
  });
}

void showProgress() {
  if (mp3->isRunning()) {
    int prog = 240 * file->getPos() / file->getSize();
    tft.fillRoundRect(40, 120, prog, 10, 3, TFT_RED);
    auto led = random(0x010101, 0xffffff);
    payLEDShow(led);
  }
}

void loop() {
  if (mp3->isRunning()) {
    mp3->loop();
  }
  if (millis() - lastMs >= 1000) {
    lastMs = millis();
    ArduinoOTA.handle();
    showProgress();
  }
}